package cn.wolfcode.crm.util;


import cn.wolfcode.crm.domain.Operator;
import cn.wolfcode.crm.domain.SystemLog;
import cn.wolfcode.crm.mapper.SystemLogMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.Setter;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

@Setter
@Getter
public class SystemLogAspect {
    private SystemLogMapper systemLogMapper;

    public void setSystemLogMapper(SystemLogMapper systemLogMapper) {
        this.systemLogMapper = systemLogMapper;
    }

    public void writeLog(JoinPoint joinPoint) throws Exception {
        SystemLog log = new SystemLog();

        Operator operator = (Operator) SecurityUtils.getSubject().getPrincipal();
        System.out.println(operator);
        if (operator != null) {
            log.setOpUser(operator);

        }

        log.setOpTime(new Date());

        String functionName = joinPoint.getSignature().getDeclaringTypeName() + ":" + joinPoint.getSignature().getName();
        log.setFunction(functionName);

        String args = new ObjectMapper().writeValueAsString(joinPoint.getArgs());
        log.setParams(args);

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String ip = attributes.getRequest().getRemoteAddr();

        log.setOpIp(ip);
        systemLogMapper.insert(log);
    }
}
